package io.kimmking.rpcfx.client;
  
import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.api.RpcfxRequest;
import io.kimmking.rpcfx.tcp.CustomTcpMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
@ChannelHandler.Sharable
public class HttpClientAsyncHandler extends ChannelInboundHandlerAdapter {
    private final CountDownLatch latch = new CountDownLatch(1);
    private String response;

    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof CustomTcpMessage) {
            CustomTcpMessage rec = (CustomTcpMessage) msg;
            String body = rec.getBody();
            String header = rec.getHeader();
            System.out.println("rec header:"+header);
            System.out.println("rec body:"+body);
            response = body;
            latch.countDown();
        }
    }


    /**
     * 阻塞等待结果后返回
     * @return 后台服务器响应
     * @throws InterruptedException exception
     */
    protected  String getResponse() throws InterruptedException {
        latch.await();

        return response;
    }
}